class Solution:
    def numTriplets(self, nums1: list, nums2: list) -> int:
        def func(numMapA, numMapB, visited):
            res = 0
            for numA in numMapA.keys():
                for numB in numMapB.keys():
                    div, mod = divmod(numA**2, numB)
                    if div == 0 or mod > 0:
                        continue
                    if div not in numMapB:
                        continue
                    a = max(numB, div)
                    b = min(numB, div)
                    if (a, b) in visited:
                        continue
                    val = 0
                    if div == numB:
                        if numMapB[div] > 1:
                            val += ((numMapB[div] - 1)**2 +
                                    (numMapB[div] - 1)) // 2
                    else:
                        val += numMapB[div] * numMapB[numB]
                    val *= numMapA[numA]
                    res += val
                    visited.add((a, b))
            return res

        map1 = {}
        map2 = {}
        for i in range(len(nums1)):
            if nums1[i] not in map1:
                map1[nums1[i]] = 0
            map1[nums1[i]] += 1
        for i in range(len(nums2)):
            if nums2[i] not in map2:
                map2[nums2[i]] = 0
            map2[nums2[i]] += 1
        res1 = func(map1, map2, set())
        res2 = func(map2, map1, set())
        return res1 + res2
